package gptma.fo.servlet;

import gptma.bo.auth.UserRoles;
import gptma.bo.model.employee.Employee;
import gptma.bo.services.employee.EmployeeServices;
import gptma.fo.controler.Session;

import java.io.IOException;
import javax.annotation.security.DeclareRoles;

import javax.ejb.EJB;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Redirection servlet after a successful login attempt: - browser asks for
 * /pages/doLogin (welcome-file) - server redirects for login.jsf because of
 * authent - upon sucessfull login, server redirects to originally requested
 * page: /pages/doLogin - the later page is in fact a servlet which performs
 * redirection
 * 
 * @author xcl
 * 
 */
@WebServlet(urlPatterns = "/pages/doLogin")
@DeclareRoles({ UserRoles.ROLE_EMPLOYEE, UserRoles.ROLE_CHIEF,
		UserRoles.ROLE_ADMIN })
public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = -4343450141408489953L;

	private static final Logger log = LoggerFactory.getLogger(LoginServlet.class);

	@EJB
	private EmployeeServices employeeServices;

	@Inject
	private Session sess;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		String trigram = req.getRemoteUser();

		log.info("New authenticated user login in: {}", trigram);

		Employee e = employeeServices.findEmployee(trigram);

		sess.setCurrentUser(e);

		if (req.isUserInRole(UserRoles.ROLE_CHIEF)
				|| req.isUserInRole(UserRoles.ROLE_ADMIN)) {
			req.getRequestDispatcher("/pages/req-list.jsf").forward(req, res);
		} else {
			req.getRequestDispatcher("/pages/imp-weekly.jsf").forward(req, res);
		}
	}

}
